<?php


namespace Biz\service\activity\project;

use App\Admin\Extensions\Tools\UserButton;
use Biz\cache\activity\CBizProject;
use Biz\model\activity\BizProjectCategoryModel;
use Biz\model\activity\BizProjectContractModel;
use Biz\model\activity\BizProjectCustomerModel;
use Biz\model\activity\BizProjectGroupModel;
use Biz\model\activity\BizProjectMcnModel;
use Biz\model\activity\BizProjectModel;
use Biz\model\activity\BizProjectPRelationIdsModel;
use Biz\model\activity\BizProjectPrepareModel;
use Biz\model\activity\BizProjectResponsibilityModel;
use Doraemon\model\Admin\BeerUsUser;
use Doraemon\model\Admin\BeerUsUser as AdminUsers;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log;
use Encore\Admin\Form\NestedForm;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;
use Exception;
use Hhz\AdministrativeRegion\Region;

class BizProjectProject extends BizProjectPageTpl
{

    const TPL_CONFIG_TPL_NAME = '商业项目';

    const CUSTOMER_TYPE_MAP = [
        '新客户', '老客户'
    ];
    const CUSTOMER_AREA_MAP = [
        '华东', '华南', '华北'
    ];
    const CUSTOMER_LEVEL_MAP = [
        'A3', 'A2', 'A1', 'B3', 'B2', 'B1', 'C2', 'C1'
    ];
    const COMPANY_TYPE_MAP = [
        '直客', '代理'
    ];
    const PROCESS_STATE_MAP = [
        '未启动', '执行中', '暂停', '执行完毕', '已结案', '撤单'
    ];
    const PROCESS_CONSISTENT_MAP = [
        '一致', '不一致'
    ];
    const PROCESS_DIFFERENT_MAP = [
        '无差异', '有差异'
    ];
    const PROJECT_TYPE_MAP = [
        '售前支持', '确认下单'
    ];
    const PROJECT_SUBJECT_MAP = [
        '家宅融智', '家宅一生', '融智上海'
    ];

    const PROJECT_NEED_MCN_MAP = [
        '不需要','需要',
    ];
    const PROJECT_NEED_MCN_SOURCE_MAP = [
        '赠机','借机','探店','家中已有','不涉及',
    ];
    const PROJECT_NEED_MCN_FORM_MAP = [
        '硬装-空间改造','硬装-局部改造','家电-可移动式','家电-嵌入式','家电-安装式','家具','软装','日用百货',
    ];
    const PROJECT_NEED_MCN_OUT_MAP = [
        '动态-轻量级','动态-重安装','动态-其他','文章','视频-vlog','视频-家在中国','视频-入户拍摄','整屋-空间1','整屋-空间2到3','整屋-其他','长续型-硬广','长续型-软植','其他-已有内容二改','其他-铺量包','非标资源',
    ];

    public ?int $total = null;
    public float $total_project_money = 0;
    private bool $send = true;
    private array $fieldAuth = [];

    public function exportDisplay()
    {
        $resource = $this->getExportList();
        $header = [
            '创建时间',
            '品牌名称', '合作品类', '合作产品', '客户类型', '客户分级','客户所属区域', '客户地理位置', '客户基础信息', '客户特征',
            '项目下单类型', '客户明确合作意向沟通凭证', '项目编号', '项目主体', '项目名称', '项目金额', '项目周期', '签约公司类型', '签约公司名称', '签约公司对接方式', '返点比例', '返点金额', '项目资料云盘链接',
            '合作内容', '上线时间', 'KPI', '备注说明',
            '销售', 'MCN', '策划', '媒介', 'PM', '财务', '法务',
            '项目状态', '项目结案时间', '项目结案云盘链接', '项目执行备注', '项目亮点', '项目问题', '项目问题解决方案', '后续建议', '客户需求与交付是否一致', '客户需求与交付差异点', '策划方案到执行落地交付差异性', '策划方案到执行落地交付差异点', '项目满意度',
            '合同订立时间', '合同归档时间', '合同邮寄快递单号', '合同链接',
            '预计首款收款金额', '实际首款收款金额', '预计首款收款时间', '实际首款收款时间', '首款开票时间', '首款开票金额', '首款发票号码', '首款发票快递单号', '预计中款收款金额', '实际中款收款金额', '预计中款收款时间', '实际中款收款时间', '中款开票时间', '中款开票金额', '中款发票号码', '中款发票快递单号', '预计尾款收款金额', '实际尾款收款金额', '预计尾款收款时间', '实际尾款收款时间', '尾款开票时间', '尾款开票金额', '尾款发票号码', '尾款发票快递单号', '收款情况备注', '收款状态备注',
        ];
        $endHeader = ['成本预估金额', '成本预估占比', '实际成本金额', '实际成本占比', '项目成本云盘链接',];
        $ids = $resource ? array_column($resource, 'id') : [];
        $condition = ['ORDER' => ['sort' => 'ASC', 'id' => 'ASC'], 'LIMIT' => [$this->getOffset(), $this->getPageSize()], 'project_id' => $ids];
        $contract = $ids ? BizProjectContractModel::dataSelect($condition + BizProjectContractModel::statusCondition()) : [];

        $contractMap = [];
        foreach ($contract as $v) {
            $contractMap[$v['project_id']][] = $v;
        }
        $addColumn = 0;
        foreach ($contractMap as $item) {
            $addColumn = max($addColumn, count($item));
        }
        //预计第4笔款收款金额
        $addHeader = [];
        for ($i = 0; $i < $addColumn; $i++) {
            //  预计三期款收款金额  实际三期款收款金额 预计三期款收款时间	实际三期款收款时间 三期款开票时间 三期款开票金额 三期款发票号码 三期款发票快递单号
            $name = BizProjectContract::CONTRACT_AMOUNT_NAME[$i] ?? $i;
            $addHeader = array_merge($addHeader, [
                "预计{$name}期款收款金额",
                "实际{$name}期款收款金额",
                "预计{$name}期款收款时间",
                "实际{$name}期款收款时间",
                "{$name}期款开票时间",
                "{$name}期款开票金额",
                "{$name}期款发票号码",
                "{$name}期款发票快递单号",
            ]);
        }
        $len = ['一','二','三','四','五','六','七','八','九','十','十一','十二','十三'];
        $addRebateColumn = 0;//project_rebates
        foreach ($resource as $v) {
            $project_rebates = $v['project_rebates'];
            if ($project_rebates) {
                $project_rebates = json_decode($project_rebates, true);
                $addRebateColumn = max($addRebateColumn, count($project_rebates));
            }
        }
        $rebateHeader = [];
        for ($i = 0; $i < $addRebateColumn; $i++) {
            //  预计三期款收款金额  实际三期款收款金额 预计三期款收款时间	实际三期款收款时间 三期款开票时间 三期款开票金额 三期款发票号码 三期款发票快递单号
            $name = $len[$i] ?? $i;
            $rebateHeader = array_merge($rebateHeader, [
                "第{$name}笔返点发票收票时间",
                "第{$name}笔返点发票金额",
                "第{$name}笔返点支付时间",
                "第{$name}笔返点备注",
            ]);
        }
        $header = array_merge($header, $addHeader, $rebateHeader, $endHeader);
        $len = count($header);
        $topHeader = array_fill(0, $len, '');
        $customerMap = BizProjectCustomerModel::adminList();
        $categoryMap = BizProjectCategoryModel::adminNameOptions();
        $instance = \Biz\service\activity\project\ExportToolsBizProject::getInstance();
        $letters = $instance->makePCoordinate($len);
        $pos = [
            1 => 9,
            1 + 9 => 17,
            1 + 9 + 17 => 7,
            1 + 9 + 17 + 7 => 13,
            1 + 9 + 17 + 7 + 13 => 4,
            1 + 9 + 17 + 7 + 13 + 4 => 26 + $addColumn * 8,
            1 + 9 + 17 + 7 + 13 + 4 + 26 + $addColumn * 8 => $addRebateColumn * 4,
            1 + 9 + 17 + 7 + 13 + 4 + 26 + $addColumn * 8 + $addRebateColumn * 4 => 5,
        ];
        $combineColumn = [];
        $headerName = ['客户信息', '项目信息', '项目责任方', '项目执行状态', '合同签约信息', '合同收款信息', '返点信息', '项目成本'];
        foreach ($pos as $s => $len) {
            $combineColumn[] = sprintf("%s1:%s1", $letters[$s], $letters[$s + $len - 1]);
            $topHeader[$s] = array_shift($headerName);
        }
        $start = 3;
        $list = [$topHeader, $header];
        $fieldAuth = BizProjectGroup::fieldAuth($this->adminId());
        //获取达人信息
        $mcn = $ids ? BizProjectMcnModel::dataSelect(['project_id' => $ids] + BizProjectMcnModel::statusCondition()) : [];
        $mcnMap = [];
        if ($mcn) {
            $uids = array_column($mcn, 'uid');
            $profiles = \Doraemon\service\UserPortrait\UserPortraitApi::request($uids, ['fans_num','product_level','nick','user_business_layer']);
            foreach ($mcn as $v) {
                $mcnMap[$v['project_id']][] = $v;
            }
        }
        extract($fieldAuth);

        $mcnData = [];
        foreach ($resource as $k => $v) {
            if (!empty($mcnMap[$v['id']])) {
                foreach ($mcnMap[$v['id']] as $mcnRow) {
                    $profile = $profiles[$mcnRow['uid']] ?? [];
                    $mcnData[] = [
                        date("Ymd", strtotime($v['created_at'])),
                        $v['project_no'],
                        $v['project_name'],
                        self::PROJECT_NEED_MCN_SOURCE_MAP[$v['project_mcn_source']],
                        self::PROJECT_NEED_MCN_FORM_MAP[$v['project_mcn_form']],
                        self::PROJECT_NEED_MCN_OUT_MAP[$v['project_mcn_out']],
                        $v['project_mcn_out_text'],
                        $v['project_mcn_product'],
                        $mcnRow['uid'],
                        $profile['nick'] ?? '-',
                        $profile['fans_num'] ?? '-',
                        $profile['product_level'] ?? '-',
                        $profile['user_business_layer'] ?? '-',
                        $mcnRow['publish_time'],
                        $mcnRow['publish_link'],
                        $mcnRow['cost'],
                        $mcnRow['other_cost'],
                        $mcnRow['submit_time'],
                        $mcnRow['exec_time'],
                        $mcnRow['kol_time'],
                        $v['project_mcn_memo'],
                    ];
                }
            }

            $project_contract = $v['project_contract'];
            $contractAmount = $contractMap[$v['id']] ?? [];
            $project_rebates = $v['project_rebates'];
            if ($project_rebates) {
                $project_rebates = json_decode($project_rebates, true);
            }
            if (empty($project_contract)) continue;
            $project_contract = json_decode($project_contract, true);
            $combine = count($project_contract);
            if ($combine > 1) {
                foreach ($letters as $letter) {
                    if (in_array($letter, ['X', 'Y', 'Z'])) continue;
                    $combineColumn[] = sprintf("%s%d:%s%d", $letter, $start, $letter, $start + $combine - 1);
                }
            }
            $start += $combine;
            $tempCustomer = $customerMap[$v['customer_name']] ?? [];
            foreach ($project_contract as $i => $vv) {
                $i++;
                $content = $vv['content'] ?? '';
                $online_date = ($vv['online_date_start'] ?? '') . " ~ " . ($vv['online_date_end'] ?? '');
                $kpi = $vv['kpi'];
                //数据开始拼接
                $temp = [
                    date("Ymd", strtotime($v['created_at'])),
                ];
                //客户信息
                $temp[] = $this->exportField($customer['name']) ? ($tempCustomer['name'] ?? '-') : '';
                $temp[] = $this->exportField($customer['category']) ? (is_array($v['customer_category']) ? implode(',', $v['customer_category']) : ($categoryMap[$v['customer_category']] ?? '-')) : '';
                $temp[] = $this->exportField($customer['product']) ? $v['customer_product'] : '';
                $temp[] = $this->exportField($customer['type']) ? (self::CUSTOMER_TYPE_MAP[$v['customer_type']] ?? '-') : '';
                $temp[] = $this->exportField($customer['level']) ? (self::CUSTOMER_LEVEL_MAP[$v['customer_level']] ?? '-') : '';
                $temp[] = $this->exportField($customer['area']) ? (self::CUSTOMER_AREA_MAP[$tempCustomer['customer_area'] ?? ''] ?? '-') : '';
                $temp[] = $this->exportField($customer['area_code']) ? (Region::getNameByCode($tempCustomer['customer_area_code'] ?? '')) : '';
                $temp[] = $this->exportField($customer['area_code']) ? ($tempCustomer['customer_intro'] ?? '-') : '';
                $temp[] = $this->exportField($customer['area_code']) ? ($tempCustomer['customer_features'] ?? '-') : '';

                //项目信息
                $temp[] = $this->exportField($project['type']) ? (self::PROJECT_TYPE_MAP[$v['project_type']] ?? '-') : '';
                $temp[] = $this->exportField($project['img']) ? (ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $v['project_img'], ImgUrl::IMAGE_SIZE_OP_ORI)) : '';
                $temp[] = $this->exportField($project['no']) ? $v['project_no'] : '';
                $temp[] = $this->exportField($project['subject']) ? (self::PROJECT_SUBJECT_MAP[$v['project_subject']] ?? '-') : '';
                $temp[] = $this->exportField($project['name']) ? $v['project_name'] : '';
                $temp[] = $this->exportField($project['money']) ? $v['project_money'] : '';
                $temp[] = $this->exportField($project['start_date']) ? $v['project_time'] : '';
                $temp[] = $this->exportField($project['company_type']) ? (self::COMPANY_TYPE_MAP[$v['project_company_type']] ?? '-') : '';
                $temp[] = $this->exportField($project['company_name']) ? $v['project_company_name'] : '';
                $temp[] = $this->exportField($project['company_contact']) ? $v['project_company_contact'] : '';
                $temp[] = $this->exportField($project['rebate_rate']) ? $v['project_rebate_rate'] : '';
                $temp[] = $this->exportField($project['rebate']) ? $v['project_rebate'] : '';
                $temp[] = $this->exportField($project['external_link']) ? $v['project_external_link'] : '';
                $projectPartTemp = $this->exportField($project['contracts']) ? [
                    $content,
                    $online_date,
                    $kpi,
                ] : array_fill(0, 3, '');
                $temp = array_merge($temp, $projectPartTemp);
                $temp[] = $this->exportField($project['memo']) ? $v['project_memo'] : '';

                //项目责任方
                $temp[] = $this->exportField($responsible['seller']) ? implode(',', $v['responsible_seller']) : '';
                $temp[] = $this->exportField($responsible['mcn']) ? implode(',', $v['responsible_mcn']) : '';
                $temp[] = $this->exportField($responsible['planner']) ? implode(',', $v['responsible_planner']) : '';
                $temp[] = $this->exportField($responsible['medium']) ? implode(',', $v['responsible_medium']) : '';
                $temp[] = $this->exportField($responsible['pm']) ? implode(',', $v['responsible_pm']) : '';
                $temp[] = $this->exportField($responsible['finance']) ? implode(',', $v['responsible_finance']) : '';
                $temp[] = $this->exportField($responsible['legal']) ? implode(',', $v['responsible_legal']) : '';

                //项目执行状态
                $temp[] = $this->exportField($process['state']) ? (self::PROCESS_STATE_MAP[$v['process_state']] ?? '-') : '';
                $temp[] = $this->exportField($process['end_date']) ? $v['process_end_date'] : '';
                $temp[] = $this->exportField($process['external_link']) ? $v['process_external_link'] : '';
                $temp[] = $this->exportField($process['memo']) ? $v['process_memo'] : '';
                $temp[] = $this->exportField($process['spot']) ? $v['process_spot'] : '';
                $temp[] = $this->exportField($process['problem']) ? $v['process_problem'] : '';
                $temp[] = $this->exportField($process['solve']) ? $v['process_solve'] : '';
                $temp[] = $this->exportField($process['advice']) ? $v['process_advice'] : '';
                $temp[] = $this->exportField($process['consistent']) ? (self::PROCESS_CONSISTENT_MAP[$v['process_consistent']] ?? '-') : '';
                $temp[] = $this->exportField($process['consistent_memo']) ? $v['process_consistent_memo'] : '';
                $temp[] = $this->exportField($process['different']) ? (self::PROCESS_DIFFERENT_MAP[$v['process_different']] ?? '-') : '';
                $temp[] = $this->exportField($process['different_memo']) ? $v['process_different_memo'] : '';
                $temp[] = $this->exportField($process['feedback']) ? $v['process_feedback'] : '';

                //合同签约信息
                $temp[] = $this->exportField($contract['create_time']) ? $v['contract_create_time'] : '';
                $temp[] = $this->exportField($contract['archive_time']) ? $v['contract_archive_time'] : '';
                $temp[] = $this->exportField($contract['express_no']) ? $v['contract_express_no'] : '';
                $temp[] = $this->exportField($contract['external_link']) ? $v['contract_external_link'] : '';
                //合同收款信息
                $temp[] = $this->exportField($contract['anticipated_initial']) ? $v['project_anticipated_initial'] : '';
                $temp[] = $this->exportField($contract['initial']) ? $v['contract_initial'] : '';
                $temp[] = $this->exportField($contract['anticipated_initial_time']) ? $v['project_anticipated_initial_time'] : '';
                $temp[] = $this->exportField($contract['initial_time']) ? $v['contract_initial_time'] : '';
                $temp[] = $this->exportField($contract['initial_bill_time']) ? $v['contract_initial_bill_time'] : '';
                $temp[] = $this->exportField($contract['initial_bill_amount']) ? $v['contract_initial_bill_amount'] : '';
                $temp[] = $this->exportField($contract['initial_title']) ? $v['contract_initial_title'] : '';
                $temp[] = $this->exportField($contract['initial_express_no']) ? $v['contract_initial_express_no'] : '';

                $temp[] = $this->exportField($contract['anticipated_middle']) ? $v['project_anticipated_middle'] : '';
                $temp[] = $this->exportField($contract['middle']) ? $v['contract_middle'] : '';
                $temp[] = $this->exportField($contract['anticipated_middle_time']) ? $v['project_anticipated_middle_time'] : '';
                $temp[] = $this->exportField($contract['middle_time']) ? $v['contract_middle_time'] : '';
                $temp[] = $this->exportField($contract['middle_bill_time']) ? $v['contract_middle_bill_time'] : '';
                $temp[] = $this->exportField($contract['middle_bill_amount']) ? $v['contract_middle_bill_amount'] : '';
                $temp[] = $this->exportField($contract['middle_title']) ? $v['contract_middle_title'] : '';
                $temp[] = $this->exportField($contract['middle_express_no']) ? $v['contract_middle_express_no'] : '';

                $temp[] = $this->exportField($contract['anticipated_tail']) ? $v['project_anticipated_tail'] : '';
                $temp[] = $this->exportField($contract['tail']) ? $v['contract_tail'] : '';
                $temp[] = $this->exportField($contract['anticipated_tail_time']) ? $v['project_anticipated_tail_time'] : '';
                $temp[] = $this->exportField($contract['tail_time']) ? $v['contract_tail_time'] : '';
                $temp[] = $this->exportField($contract['tail_bill_time']) ? $v['contract_tail_bill_time'] : '';
                $temp[] = $this->exportField($contract['tail_bill_amount']) ? $v['contract_tail_bill_amount'] : '';
                $temp[] = $this->exportField($contract['tail_title']) ? $v['contract_tail_title'] : '';
                $temp[] = $this->exportField($contract['tail_express_no']) ? $v['contract_tail_express_no'] : '';
                $temp[] = $this->exportField($contract['memo']) ? $v['contract_memo'] : '';
                $temp[] = $this->exportField($contract['state_memo']) ? $v['contract_state_memo'] : '';

                //其它收款
                $tempContractAmount = [];
                foreach ($contractAmount as $contractAmountItem) {
                    $tempContractAmount = array_merge($tempContractAmount, [
                        $contractAmountItem['anticipated_amount'],
                        $contractAmountItem['actual_amount'],
                        $contractAmountItem['anticipated_time'],
                        $contractAmountItem['actual_time'],
                        $contractAmountItem['bill_time'],
                        $contractAmountItem['bill_amount'],
                        $contractAmountItem['bill_no'],
                        $contractAmountItem['bill_express_no'],
                    ]);
                }
                $tempContractAmount = $this->exportField($contract['other_data']) ? ($tempContractAmount + array_fill(0, 8 * $addColumn, '')) : array_fill(0, 8 * $addColumn, '');
                //返点信息
                $tempRebate = [];
                if ($project_rebates) {
                    foreach ($project_rebates as $project_rebates_item) {
                        $tempRebate = array_merge($tempRebate, [
                            $project_rebates_item['title_date'],
                            $project_rebates_item['amount'],
                            $project_rebates_item['pay_date'],
                            $project_rebates_item['memo'],
                        ]);
                    }
                }
                $tempRebate = $this->exportField($rebate['rebate']) ? ($tempRebate + array_fill(0, 4 * $addRebateColumn, '')) : array_fill(0, 4 * $addRebateColumn, '');
                $temp = array_merge($temp, $tempContractAmount, $tempRebate);

                //项目成本
                $temp[] = $this->exportField($costs['estimate']) ? $v['costs_estimate'] : '';
                $temp[] = $this->exportField($costs['estimated_proportion']) ? $v['costs_estimated_proportion'] : '';
                $temp[] = $this->exportField($costs['real']) ? $v['costs_real'] : '';
                $temp[] = $this->exportField($costs['real_proportion']) ? $v['costs_real_proportion'] : '';
                $temp[] = $this->exportField($costs['external_link']) ? $v['costs_external_link'] : '';

                $list[] = $temp;
            }
        }

        if ($this->exportField($mcn['mcn'])) {
            $headerData = [
                ['创建时间','项目编号','项目名称','合作产品来源','产品合作形式','产出形式','产出形式补充','产品','uid','昵称','粉丝数','创作者等级','商业等级','发布时间','发布链接','稿费成本','其他成本','提报业绩结算时间','执行业绩结算时间','KOL结算时间','合作备注'],
            ];
            $instance::addSheet(array_merge($headerData, $mcnData), '达人信息');
        }
        $instance::create(date("YmdHis") . '商业项目列表', $list, $combineColumn);
    }

    public static function generateProjectNo()
    {
        $id = CBizProject::incrDateCounter(date("Y"));
        //RZGG+当前年份+三位序号
        $no = sprintf("%03d", $id);
        return "RZGG" . date("Y") . $no;
    }

    public function condition(): array
    {
        $this->fieldAuth = BizProjectGroup::fieldAuth($this->adminId());
        $customer_name = $this->getRequest()->input('customer_name', '');
        $customer_category = $this->getRequest()->input('customer_category', '');
        $user = $this->getRequest()->input('responsibility', '');
        $project_start_date = $this->getRequest()->input('project_date.start', '');
        $project_end_date = $this->getRequest()->input('project_date.end', '');
        $created_at_start_date = $this->getRequest()->input('created_at.start', '');
        $created_at_end_date = $this->getRequest()->input('created_at.end', '');
        $project_no = $this->getRequest()->input('project_no', '');
        $project_name = $this->getRequest()->input('project_name', '');
        $process_state = $this->getRequest()->input('process_state', '');
        $condition = [];
        if ($process_state) $condition['process_state'] = $process_state;
        if ($project_name) $condition['project_name[~]'] = $project_name;
        if ($project_no) $condition['project_no[~]'] = $project_no;
        if ($customer_name) $condition['customer_name'] = $customer_name;
        $findError = false;
        $findIds = [];
        if ($customer_category) {
            $findProject = BizProjectPRelationIdsModel::findProjectPid($customer_category);
            if ($findProject) {
                $findIds = empty($findIds) ? $findProject : array_intersect($findProject, $findIds);
            } else {
                $findError = true;
            }
        }
        if ($user) {
            BizProjectResponsibilityModel::findProjectByAdmin($user);
            $findProject = BizProjectResponsibilityModel::afterFindProject();
            if ($findProject) {
                $findIds = empty($findIds) ? $findProject : array_intersect($findProject, $findIds);
            } else {
                $findError = true;
            }
        }
        if ($project_start_date && $project_end_date) {
            $condition['OR #project_date'] = [
                'project_start_date[<>]' => [$project_start_date, $project_end_date],
                'project_end_date[<>]' => [$project_start_date, $project_end_date],
                'AND' => [
                    'project_start_date[<]' => $project_start_date,
                    'project_end_date[>]' => $project_end_date,
                ]
            ];
        } elseif ($project_start_date) {
            $condition['project_end_date[>=]'] = $project_start_date;
        } elseif ($project_end_date) {
            $condition['project_start_date[<=]'] = $project_end_date;
        }

        if ($created_at_start_date && $created_at_end_date) {
            $condition['created_at[<>]'] = [$created_at_start_date, $created_at_end_date];
        } elseif ($created_at_start_date) {
            $condition['created_at[>=]'] = $created_at_start_date;
        } elseif ($created_at_end_date) {
            $condition['created_at[<=]'] = $created_at_end_date;
        }

        //权限
        if (!$this->isAdmin()) {
            //每个用户进入后仅能看到自己所属责任方的项目
            //销售leader可见自己组员所属责任方的所有项目
            $findProject = self::findAuthModuleIds($this->adminId());
            if ($findProject) {
                $findIds = empty($findIds) ? $findProject : array_intersect($findProject, $findIds);
            } else {
                $findError = true;
            }
        }
        if ($findError) return ['id' => 0];
        if ($findIds) $condition['id'] = array_values($findIds);
        return $condition;
    }

    public function withInfoHtml(): array
    {
        $group = BizProjectGroupModel::getGroupNameByAdminId($this->adminId());
        $list = BizProjectModel::getAdmList($this->getRequestCondition());
        foreach ($list as $v) {
            if (is_numeric($v['project_money'])) $this->total_project_money = bcadd($this->total_project_money, $v['project_money']);
        }
        $html = [
            "除管理员外，每个用户仅可见自己所属责任方项目及组员项目",
            "当前用户组 : " . ($group ? implode(",", $group) : ""),
        ];
        if ($this->displayForm($this->fieldAuth['project']['money'])) {
            $html[] = "项目金额总计 : " . (number_format($this->total_project_money, 2));
        }
        $html[] = "项目总数 : " . $this->getTotal();
        return ["提示", implode("<br/>", $html)];
    }

    public function getList(): array
    {
        $condition = ['ORDER' => ['id' => 'DESC']] + $this->getLimitCondition() + $this->getRequestCondition();
        return BizProjectModel::getAdmList($condition);
    }

    public function getGrid(Grid $grid)
    {
        $grid->filter(function (Grid\Filter $filter) {
            // 去掉默认的id过滤器
            $filter->disableIdFilter();
            $filter->column(1 / 2, function (Grid\Filter $filter) {
                $filter->between('project_date', '项目周期')->date();
                $filter->equal('customer_name', '品牌名称')->multipleSelect(BizProjectCustomerModel::adminNameOptions());
                $filter->equal('customer_category', '合作品类')->multipleSelect(BizProjectCategoryModel::adminNameOptions(['pid[!]' => 0]));
                $filter->equal('responsibility', '项目责任方')->multipleSelect(AdminUsers::getNameByUsername());
            });
            $filter->column(1 / 2, function (Grid\Filter $filter) {
                $filter->between('created_at', '创建时间')->datetime();
                $filter->equal('project_no', '项目编号');
                $filter->equal('project_name', '项目名称');
                $filter->equal('process_state', '项目状态')->multipleSelect(BizProjectProject::PROCESS_STATE_MAP);
            });
            if ($this->getRequestCondition()) $filter->expand();
        });
        $grid->tools(function (Grid\Tools $tool) {
            $categoryUri = BizProjectCategory::getRoute()->getListRoute();
            $tool->prepend(new UserButton(UserButton::TYPE_HREF, '', '合作品类管理', 'fa-list', admin_url($categoryUri)));
            $this->genExportButton($tool);
        });
        $grid->disableCreateButton();
        $grid->column('id', '记录id');
        if ($this->displayForm($this->fieldAuth['customer']['name'])) $grid->column('customer_name', '品牌名称')->using(BizProjectCustomerModel::adminNameOptions());
        if ($this->displayForm($this->fieldAuth['customer']['category'])) $grid->column('customer_category', '合作品类')->label();
        if ($this->displayForm($this->fieldAuth['customer']['product'])) $grid->column('customer_product', '合作产品');
        $grid->column('project_no', '项目编号');
        if ($this->displayForm($this->fieldAuth['project']['name'])) $grid->column('project_name', '项目名称');
        if ($this->displayForm($this->fieldAuth['project']['money'])) $grid->column('project_money_format', '项目金额');
        if ($this->displayForm($this->fieldAuth['project']['start_date'])) $grid->column('project_time', '项目周期');
        if ($this->displayForm($this->fieldAuth['responsible']['seller'])) $grid->column('responsible_seller', '销售')->label('warning');
        if ($this->displayForm($this->fieldAuth['responsible']['pm'])) $grid->column('responsible_pm', 'PM')->label();
        if ($this->displayForm($this->fieldAuth['responsible']['planner'])) $grid->column('responsible_planner', '策划')->label();
        if ($this->displayForm($this->fieldAuth['process']['state'])) $grid->column('process_state', '项目状态')->using(BizProjectProject::PROCESS_STATE_MAP);
        $grid->column('created_at_date', '创建时间');
        $grid->column('admin', '创建人');
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableView();
        });
        $grid->fixColumns(1);
    }

    public function displayGroupField($auth): bool
    {
        foreach ($auth as $mode) {
            if ($mode & 1) return true;
            if ($mode & 2) return true;
        }
        return false;
    }

    public array $displayField = [];
    public function getForm(Form $form)
    {
        $form->confirm('确定提交吗？');
        $nameOptions = AdminUsers::getActiveNameByIds();
        $fieldAuth = BizProjectGroup::fieldAuth($this->adminId(), $this->isCreate());
        $responsible = $fieldAuth['responsible'];
        $customer = $fieldAuth['customer'];
        $project = $fieldAuth['project'];
        $process = $fieldAuth['process'];
        $contract = $fieldAuth['contract'];
        $rebate = $fieldAuth['rebate'];
        $costs = $fieldAuth['costs'];
        $mcn = $fieldAuth['mcn'];
        if ($this->displayGroupField($responsible)) {
            $form->fieldset("项目责任方", function (Form $form) use ($nameOptions, $responsible) {
                if ($this->displayForm($responsible['seller'])) $this->disableForm($form->multipleSelect('responsible.seller', '销售')->options($nameOptions)->default([$this->adminId()])->required(), $responsible['seller']);
                if ($this->displayForm($responsible['mcn'])) $this->disableForm($form->multipleSelect('responsible.mcn', 'MCN')->options($nameOptions), $responsible['mcn']);
                if ($this->displayForm($responsible['planner'])) {
                    $form->radio('project.need_planner', '策划需求')->options(['有策划', '无策划']);
                    $this->disableForm($form->multipleSelect('responsible.planner', '策划')->options($nameOptions), $responsible['planner']);
                }
                if ($this->displayForm($responsible['medium'])) $this->disableForm($form->multipleSelect('responsible.medium', '媒介')->options($nameOptions), $responsible['medium']);
                if ($this->displayForm($responsible['pm'])) {
                    if (($responsible['pm'] & 2)) {
                        $form->table('pms', 'PM', function (NestedForm $nest) use ($nameOptions) {
                            $nest->select('pm', 'PM')->options($nameOptions)->required();
                            $nest->text('value', '分工比例')->default(1)->placeholder('仅支持填写数字，最多保存两位小数')->required();
                        })->required();
                    } elseif ($responsible['pm'] & 1) {
                        $form->display('pms', 'PM')->with(function ($contents) {
                            $tableRows = [];
                            if ($contents) {
                                foreach ($contents as $v) {
                                    $tableRows[] = [
                                        $v['pm'] ?: '-',
                                        $v['value'] ?: '-',
                                    ];
                                }
                            }
                            return (new \Encore\Admin\Widgets\Table(['PM', '分工比例'], $tableRows))->render();
                        });
                    }
                }
                if ($this->displayForm($responsible['finance'])) $this->disableForm($form->multipleSelect('responsible.finance', '财务')->options($nameOptions)->readOnly(), $responsible['finance']);
                if ($this->displayForm($responsible['legal'])) $this->disableForm($form->multipleSelect('responsible.legal', '法务')->options($nameOptions)->readOnly(), $responsible['legal']);
            });
        }
        if ($this->displayGroupField($customer)) {
            $form->fieldset("客户信息", function (Form $form) use ($customer)  {
                $customerIds = BizProjectCustomer::findIds($this->adminId());
                if ($info = $this->formInfo()) {
                    $customerIds[] = $info['customer']['name'];
                }
                $customerNameOptions = $customerIds ? BizProjectCustomerModel::adminNameOptions(['id' => $customerIds]) : [];
                $formCustomerName = $form->select('customer.name', '品牌名称')->options($customerNameOptions)->help("选择品牌后，该项目会关联该品牌在客户服务档案中的信息，相关信息请在客户服务档案中更新")->required();
                if ($this->displayForm($customer['name'])) $this->disableForm($formCustomerName, $customer['name']);
                if ($this->displayForm($customer['category'])) $this->disableForm($form->multipleSelect('customer.category', '合作品类')->options(BizProjectCategoryModel::adminNameLevelOptions())->required(), $customer['category']);
                if ($this->displayForm($customer['product'])) $this->disableForm($form->text('customer.product', '合作产品')->placeholder('填写具体合作产品名称')->required(), $customer['product']);
                if ($this->displayForm($customer['type'])) $this->disableForm($form->radio('customer.type', '客户类型')->options(BizProjectProject::CUSTOMER_TYPE_MAP)->required()->default(-1), $customer['type']);
                if (!$this->isCreate()) {
                    $areaMap = Region::getAllAreaDetail();
                    foreach ($customerNameOptions as $key => $value) {
                        $responsibilityDataForm = BizProjectCustomerModel::dataSelectInfo(['id' => $key]);
                        $formCustomerName->when($key, function (Form $form) use($key, $areaMap, $responsibilityDataForm) {
                            $form->display('customer.area', '客户所属区域')->with(function () use($responsibilityDataForm) {
                                return BizProjectProject::CUSTOMER_AREA_MAP[$responsibilityDataForm['customer_area']];
                            })->disable()->help('与品牌关联，不允许修改');
                            $form->display('responsible.seller', '客户地理位置')->with(function () use($responsibilityDataForm, $areaMap) {
                                return $areaMap[$responsibilityDataForm['customer_area_code']];
                            })->disable()->help('与品牌关联，不允许修改');;
                            $form->display('customer.area_code', '客户基础信息')->with(function () use($responsibilityDataForm) {
                                return $responsibilityDataForm['customer_intro'];
                            })->disable()->help('与品牌关联，不允许修改');;
                            $form->display('customer.intro', '客户特征')->with(function () use($responsibilityDataForm) {
                                return $responsibilityDataForm['customer_features'];
                            })->disable()->help('与品牌关联，不允许修改');;
                        });
                    }
//                    if ($this->displayForm($customer['area'])) $form->select('customer.area', '客户所属区域')->options(BizProjectProject::CUSTOMER_AREA_MAP)->disable();
//                    if ($this->displayForm($customer['area_code'])) $form->select('customer.area_code', '客户地理位置')->options(Region::getAllAreaDetail())->required()->disable();
//                    if ($this->displayForm($customer['intro'])) $form->textarea('customer.intro', '客户基础信息')->required()->disable();
//                    if ($this->displayForm($customer['features'])) $form->textarea('customer.features', '客户特征')->required()->disable();
                }
                if ($this->displayForm($customer['level'])) $this->disableForm($form->select('customer.level', '客户分级')->options(BizProjectProject::CUSTOMER_LEVEL_MAP)->required()->default(-1), $customer['level']);
            });
        }
        if ($this->displayGroupField($project)) {
            $form->fieldset("项目信息", function (Form $form) use ($project) {
                if ($this->displayForm($project['type'])) $this->disableForm($form->radio('project.type', '项目下单类型')
                        ->options(BizProjectProject::PROJECT_TYPE_MAP)->required()->default(-1)->help("售前支持：客户未下单，但有明确合作需求/意向/预算，商务流程推进中。确认下单：客户有邮件明确告知确认与好好住合作，商务流程已签署。"), $project['type']);
                if ($this->displayForm($project['img'])) $this->disableForm($form->imgUpload('project.img', '客户明确合作意向沟通凭证')->help("售前支持项目传客户明确合作意向邮件截图或文字截图，确认下单项目传客户书面下单邮件截图或文字截图"), $project['img']);
                if (!$this->isCreate() && $this->displayForm($project['no'])) $form->text('project.no', '项目编号')->readonly()->required();
                if ($this->displayForm($project['subject'])) $this->disableForm($form->radio('project.subject', '项目主体')->options(BizProjectProject::PROJECT_SUBJECT_MAP)->required()->default(-1), $project['subject']);
                if ($this->displayForm($project['name'])) $this->disableForm($form->text('project.name', '项目名称')->required(), $project['name']);
                if ($this->displayForm($project['money'])) $this->disableForm($form->text('project.money', '项目金额')->required(), $project['money']);
                if ($this->displayForm($project['start_date'])) $this->disableForm($form->dateRange('project.start_date', 'project.end_date', '项目周期(开始)')->required(), $project['start_date']);
                if ($this->displayForm($project['mcn'])) $this->disableForm($form->radio('project.mcn_uid',  '是否需要达人合作')->options(self::PROJECT_NEED_MCN_MAP)->default(-1)->required(), $project['mcn']);
                if ($this->displayForm($project['company_type'])) $this->disableForm($form->radio('project.company_type', '签约公司类型')->options(BizProjectProject::COMPANY_TYPE_MAP)->required()->default(-1), $project['company_type']);
                if ($this->displayForm($project['company_name'])) $this->disableForm($form->text('project.company_name', '签约公司名称')->required(), $project['company_name']);
                if ($this->displayForm($project['company_contact'])) $this->disableForm($form->text('project.company_contact', '签约公司对接方式'), $project['company_contact']);
                if ($this->displayForm($project['rebate_rate'])) $this->disableForm($form->text('project.rebate_rate', '返点比例（%）')->placeholder('签约公司为代理时，需填写返点比例')->help("签约公司为直客时没有返点时，返点比例填0，签约公司为代理时，请按照实际情况填写")->required(), $project['rebate_rate']);
                if ($this->displayForm($project['rebate'])) $this->disableForm($form->text('project.rebate', '返点金额')->placeholder('签约公司为代理时，需填写返点金额')->help("签约公司为直客时没有返点时，返点金额填0，签约公司为代理时，请按照实际情况填写")->required(), $project['rebate']);
                if ($this->displayForm($project['external_link'])) $this->disableForm($form->textarea('project.external_link', '项目资料云盘链接')->help("包括方案、排期资源包、MCN预判、产品及品牌资料")->required(), $project['external_link']);
                if ($this->displayForm($project['contracts'])) {
                    if (($project['contracts'] & 2)) {
                        $form->table('contracts', '合作内容', function (NestedForm $nest) {
                            $nest->text('content', '合作内容')->required();
                            $nest->textarea('kpi', 'KPI')->required();
                            $nest->dateRange('online_date_start', 'online_date_end', '上线时间')->required();
                        })->required();
                    } elseif ($project['contracts'] & 1) {
                        $form->display('contracts', '合作内容')->with(function ($contents) {
                            $tableRows = [];
                            if ($contents) {
                                foreach ($contents as $v) {
                                    $tableRows[] = [
                                        $v['content'] ?: '-',
                                        $v['kpi'] ?: '-',
                                        $v['online_date_start'] . " ~ " . $v['online_date_end']
                                    ];
                                }
                            }
                            return (new \Encore\Admin\Widgets\Table(['合作内容', 'KPI', '上线时间'], $tableRows))->render();
                        });
                    }
                }
                if ($this->displayForm($project['memo'])) $this->disableForm($form->textarea('project.memo', '备注说明')->placeholder('可填写该项目其他要求或情况说明等'), $project['memo']);
            });
        }
        if ($this->displayGroupField($mcn)) {
            $form->fieldset("达人合作", function (Form $form) use ($mcn) {
                $this->disableForm($form->select('project.mcn_source', '合作产品来源')->options(self::PROJECT_NEED_MCN_SOURCE_MAP)->default(-1) , $mcn['mcn']);
                $this->disableForm($form->select('project.mcn_form', '产品合作形式')->options(self::PROJECT_NEED_MCN_FORM_MAP)->default(-1), $mcn['mcn']);
                $this->disableForm($form->select('project.mcn_out', '产出形式')->options(self::PROJECT_NEED_MCN_OUT_MAP)->default(-1), $mcn['mcn']);
                $this->disableForm($form->text('project.mcn_out_text', '产出形式补充')->help('如选择非标资源时填写'), $mcn['mcn']);
                $this->disableForm($form->text('project.mcn_product', '产品'), $mcn['mcn']);
                if (!$this->isCreate()) {
                    $uri = BizProjectMcn::getRoute()->getListRoute($this->getFormInfoId());
                    $form->html(new UserButton(UserButton::TYPE_HREF, '', '编辑合作人选', 'fa-user', admin_url($uri)));
                    $form->display('mcn', '')->with(function ($contents) {
                        $tableRows = [];
                        if ($contents) {
                            $tableRows = $contents;
                        }
                        return (new \Encore\Admin\Widgets\Table(['uid', '昵称','粉丝数','创作者等级','商业等级'], $tableRows))->render();
                    });
                }
                $this->disableForm($form->textarea('project.mcn_memo', '合作备注')->attribute('maxlength', '500'), $mcn['mcn']);
            })->collapsed();
        }
        if ($this->displayGroupField($process)) {
            $form->fieldset('项目执行情况', function (Form $form) use ($process) {
                if ($this->displayForm($process['state'])) $this->disableForm($form->radio('process.state', '项目状态')->options(BizProjectProject::PROCESS_STATE_MAP), $process['state']);
                if ($this->displayForm($process['end_date'])) $this->disableForm($form->date('process.end_date', '项目结案时间'), $process['end_date']);
                if ($this->displayForm($process['external_link'])) $this->disableForm($form->text('process.external_link', '项目结案云盘链接'), $process['external_link']);
                if ($this->displayForm($process['memo'])) $this->disableForm($form->textarea('process.memo', '项目执行备注'), $process['memo']);
                if ($this->displayForm($process['spot'])) $this->disableForm($form->textarea('process.spot', '项目亮点')->help("如目标层、效果层、协同层、交付、客满、资源等")->attribute('maxlength', '500'), $process['spot']);
                if ($this->displayForm($process['problem'])) $this->disableForm($form->textarea('process.problem', '项目问题')->help("如目标层、效果层、协同层、交付、客满、资源等")->attribute('maxlength', '500'), $process['problem']);
                if ($this->displayForm($process['solve'])) $this->disableForm($form->textarea('process.solve', '项目问题解决方案')->help("问题是否被解决？解决方案是什么？")->attribute('maxlength', '500'), $process['solve']);
                if ($this->displayForm($process['advice'])) $this->disableForm($form->textarea('process.advice', '后续建议')->help("可复用的执行经验or优化建议举措")->attribute('maxlength', '500'), $process['advice']);
                if ($this->displayForm($process['consistent'])) $this->disableForm($form->radio('process.consistent', '客户需求与交付是否一致')->options(BizProjectProject::PROCESS_CONSISTENT_MAP), $process['consistent']);
                if ($this->displayForm($process['consistent_memo'])) $this->disableForm($form->textarea('process.consistent_memo', '客户需求与交付差异点')->help("如客户需求与交付不一致，请写明差异点")->attribute('maxlength', '500'), $process['consistent_memo']);
                if ($this->displayForm($process['different'])) $this->disableForm($form->radio('process.different', '策划方案到执行落地交付差异性')->options(BizProjectProject::PROCESS_DIFFERENT_MAP), $process['different']);
                if ($this->displayForm($process['different_memo'])) $this->disableForm($form->textarea('process.different_memo', '策划方案到执行落地交付差异点')->help("如交付差异性选择有差异，请写明差异点，如客户需求、资源形式、执行效果等")->attribute('maxlength', '500'), $process['different_memo']);
                if ($this->displayForm($process['feedback'])) $this->disableForm($form->textarea('process.feedback', '项目满意度')->help("请上传满意度表单链接")->attribute('maxlength', '500'), $process['feedback']);
            })->collapsed();
        }

        if ($this->displayGroupField(array_slice($contract, 0, 4, true))) {
            $form->fieldset("合同签约信息", function (Form $form) use ($contract) {
                if ($this->displayForm($contract['create_time'])) $this->disableForm($form->date('contract.create_time', '合同订立时间'), $contract['create_time']);
                if ($this->displayForm($contract['archive_time'])) $this->disableForm($form->date('contract.archive_time', '合同归档时间'), $contract['archive_time']);
                if ($this->displayForm($contract['express_no'])) $this->disableForm($form->text('contract.express_no', '合同邮寄快递单号'), $contract['express_no']);
                if ($this->displayForm($contract['external_link'])) $this->disableForm($form->text('contract.external_link', '合同链接'), $contract['external_link']);
            })->collapsed();
        }
        if ($this->displayGroupField(array_slice($contract, 4, -1, true))) {
            $form->fieldset("合同收款信息", function (Form $form) use ($contract) {
                if ($this->displayForm($contract['anticipated_initial'])) $this->disableForm($form->text('project.anticipated_initial', '预计首款收款金额')->help('仅数字，2位小数'), $contract['anticipated_initial']);
                if ($this->displayForm($contract['initial'])) $this->disableForm($form->text('contract.initial', '实际首款收款金额')->help('仅数字，2位小数'), $contract['initial']);
                if ($this->displayForm($contract['anticipated_initial_time'])) $this->disableForm($form->date('project.anticipated_initial_time', '预计首款收款时间'), $contract['anticipated_initial_time']);
                if ($this->displayForm($contract['initial_time'])) $this->disableForm($form->date('contract.initial_time', '实际首款收款时间'), $contract['initial_time']);
                if ($this->displayForm($contract['initial_bill_time'])) $this->disableForm($form->date('contract.initial_bill_time', '首款开票时间'), $contract['initial_bill_time']);
                if ($this->displayForm($contract['initial_bill_amount'])) $this->disableForm($form->text('contract.initial_bill_amount', '首款开票金额')->help('仅数字，2位小数'), $contract['initial_bill_amount']);
                if ($this->displayForm($contract['initial_title'])) $this->disableForm($form->text('contract.initial_title', '首款发票号码'), $contract['initial_title']);
                if ($this->displayForm($contract['initial_express_no'])) $this->disableForm($form->text('contract.initial_express_no', '首款发票快递单号'), $contract['initial_express_no']);
                if ($this->displayForm($contract['anticipated_middle'])) $this->disableForm($form->text('project.anticipated_middle', '预计中款收款金额')->help('仅数字，2位小数'), $contract['anticipated_middle']);
                if ($this->displayForm($contract['middle'])) $this->disableForm($form->text('contract.middle', '实际中款收款金额')->help('仅数字，2位小数'), $contract['middle']);
                if ($this->displayForm($contract['anticipated_middle_time'])) $this->disableForm($form->date('project.anticipated_middle_time', '预计中款收款时间'), $contract['anticipated_middle_time']);
                if ($this->displayForm($contract['middle_time'])) $this->disableForm($form->date('contract.middle_time', '实际中款收款时间'), $contract['middle_time']);
                if ($this->displayForm($contract['middle_bill_time'])) $this->disableForm($form->date('contract.middle_bill_time', '中款开票时间'), $contract['middle_bill_time']);
                if ($this->displayForm($contract['middle_bill_amount'])) $this->disableForm($form->text('contract.middle_bill_amount', '中款开票金额')->help('仅数字，2位小数'), $contract['middle_bill_amount']);
                if ($this->displayForm($contract['middle_title'])) $this->disableForm($form->text('contract.middle_title', '中款发票号码'), $contract['middle_title']);
                if ($this->displayForm($contract['middle_express_no'])) $this->disableForm($form->text('contract.middle_express_no', '中款发票快递单号'), $contract['middle_express_no']);
                if ($this->displayForm($contract['anticipated_tail'])) $this->disableForm($form->text('project.anticipated_tail', '预计尾款收款金额')->help('仅数字，2位小数'), $contract['anticipated_tail']);
                if ($this->displayForm($contract['tail'])) $this->disableForm($form->text('contract.tail', '实际尾款收款金额')->help('仅数字，2位小数'), $contract['tail']);
                if ($this->displayForm($contract['anticipated_tail_time'])) $this->disableForm($form->date('project.anticipated_tail_time', '预计尾款收款时间'), $contract['anticipated_tail_time']);
                if ($this->displayForm($contract['tail_time'])) $this->disableForm($form->date('contract.tail_time', '实际尾款收款时间'), $contract['tail_time']);
                if ($this->displayForm($contract['tail_bill_time'])) $this->disableForm($form->date('contract.tail_bill_time', '尾款开票时间'), $contract['tail_bill_time']);
                if ($this->displayForm($contract['tail_bill_amount'])) $this->disableForm($form->text('contract.tail_bill_amount', '尾款开票金额')->help('仅数字，2位小数'), $contract['tail_bill_amount']);
                if ($this->displayForm($contract['tail_title'])) $this->disableForm($form->text('contract.tail_title', '尾款发票号码'), $contract['tail_title']);
                if ($this->displayForm($contract['tail_express_no'])) $this->disableForm($form->text('contract.tail_express_no', '尾款发票快递单号'), $contract['tail_express_no']);
                if ($this->displayForm($contract['memo'])) $this->disableForm($form->text('contract.memo', '收款情况备注')->help("如果收款超出预计时间，请填写说明"), $contract['memo']);
                if ($this->displayForm($contract['state_memo'])) $this->disableForm($form->text('contract.state_memo', '收款状态备注'), $contract['state_memo']);
                if (!$this->isCreate()) {
                    $customerUri = BizProjectContract::getRoute()->getListRoute($this->getFormInfoId());
                    $list = BizProjectContractModel::dataSelect(['project_id' => $this->getFormInfoId()] + BizProjectContractModel::statusCondition());
                    $response = [];
                    if ($list) {
                        foreach ($list as $i => $v) {
                            $response[] = $v + [
                                    'name' => BizProjectContract::getAccountName($i),
                                    'created_at_date' => $v['created_at'],
                                ];
                        }
                    }
                    if ($this->displayForm($contract['other_data'])) {
                        $form->html(new UserButton(UserButton::TYPE_HREF, '', '编辑其它合同收款信息', 'fa-user', admin_url($customerUri)));
                        $form->display('other_data', '其它合同收款信息')->with(function () use ($response) {
                            $tableRows = [];
                            foreach ($response as $v) {
                                $tableRows[] = [
                                    $v['name'] ?: '-', $v['anticipated_amount'] ?: '-', $v['actual_amount'] ?: '-', $v['anticipated_time'] ?: '-', $v['actual_time'] ?: '-'
                                ];
                            }
                            return (new \Encore\Admin\Widgets\Table(['收款信息', '预计收款金额', '实际收款金额', '预计收款时间', '实际收款时间'], $tableRows))->render();
                        });
                    }
                }
            })->collapsed();
        }

        if ($this->displayGroupField($rebate)) {
                $form->fieldset("返点信息", function (Form $form) use ($rebate) {
                    if ($rebate['rebate'] & 2) {
                        $form->table('rebates', ' ', function (NestedForm $nest) {
                            $nest->date('title_date', '返点发票收票时间')->required();
                            $nest->text('amount', '返点发票金额')->required();
                            $nest->date('pay_date', '返点支付时间')->required();
                            $nest->textarea('memo', '返点备注')->required();
                        })->required();
                    } else {
                        $form->display('rebates', ' ')->with(function ($contents) {
                            $tableRows = [];
                            if ($contents) {
                                foreach ($contents as $v) {
                                    $tableRows[] = [
                                        $v['title_date'] ?: '-',
                                        $v['amount'] ?: '-',
                                        $v['pay_date'] ?: '-',
                                        $v['memo']  ?: "-",
                                    ];
                                }
                            }
                            return (new \Encore\Admin\Widgets\Table(['返点发票收票时间', '返点发票金额', '返点支付时间', '返点备注'], $tableRows))->render();
                        });
                    }
                })->collapsed();

        }
        if ($this->displayGroupField($costs)) {
            $form->fieldset('项目成本', function (Form $form) use ($costs) {
                if ($this->displayForm($costs['estimate'])) $this->disableForm($form->text('costs.estimate', '成本预估金额')->help('仅数字，2位小数'), $costs['estimate']);
                if ($this->displayForm($costs['estimated_proportion'])) $this->disableForm($form->text('costs.estimated_proportion', ' 成本预估占比（%）')->help('仅数字，2位小数'), $costs['estimated_proportion']);
                if ($this->displayForm($costs['real'])) $this->disableForm($form->text('costs.real', '实际成本金额')->help('仅数字，2位小数'), $costs['real']);
                if ($this->displayForm($costs['real_proportion'])) $this->disableForm($form->text('costs.real_proportion', '实际成本占比（%）')->help('仅数字，2位小数'), $costs['real_proportion']);
                if ($this->displayForm($costs['external_link'])) $this->disableForm($form->text('costs.external_link', '项目成本云盘链接'), $costs['external_link']);
            })->collapsed();
        }
    }

    public function getFormInfo($id): array
    {
        return BizProjectModel::getAdmInfo($id);
    }

    public function getDefaultFormInfo(): array
    {
        $pre = $this->getRequest()->input('pre_id', 0);
        $response = [];
        if ($pre) {
            $info = BizProjectPrepareModel::getAdmInfo($pre);
            if ($info) {
                $response = [
                    'responsible' => [
                        'planner' => $info['responsible']['planner'],
                        'medium' => $info['responsible']['medium'],
                    ],
                    'customer' => [
                        'name' => $info['project_customer_name'],
                        'category' => $info['project_category'],
                        'product' => $info['project_product'],
                        'type' => $info['customer_type'],
                        'level' => $info['customer_level'],
                    ],
                    'project' => [
                        'name' => $info['project_name'],
                    ],
                ];
            }
        }
        return $response;
    }

    /**
     * @throws Exception
     */
    public function save($input)
    {
        $all = $input;
        $id = $all['id'] ?? 0;
        $formatParam = BizProjectModel::formatAdmSaveInfo($all);
        $fieldAuth = BizProjectGroup::fieldAuth($this->adminId(), $id == 0);
        extract($fieldAuth); //$responsible $customer $project $process $contract $rebate $costs

        //项目责任方
        $responsibleRequest = $formatParam['responsible'] ?? [];
        $projectRequest = $formatParam['project'] ?? [];
        if (!$this->saveForm($responsible['seller'])) unset($responsibleRequest['responsible_seller']);
        if (!$this->saveForm($responsible['mcn'])) unset($responsibleRequest['responsible_mcn']);
        if (!$this->saveForm($responsible['planner'])) {
            unset($responsibleRequest['responsible_planner']);
        } else {
            $needPlanner = $projectRequest['project_need_planner'];
            if ($needPlanner == 0 && empty($responsibleRequest['responsible_planner'])) {
                throw new Exception('策划不能为空');
            }
        }
        if (!$this->saveForm($responsible['medium'])) unset($responsibleRequest['responsible_medium']);
        if (!$this->saveForm($responsible['pm'])) {
            unset($responsibleRequest['responsible_pm']);
            unset($responsibleRequest['pm_extra']);
        }
        if (!$this->saveForm($responsible['finance'])) unset($responsibleRequest['responsible_finance']);
        if (!$this->saveForm($responsible['legal'])) unset($responsibleRequest['responsible_legal']);

        $extend = [];
        //客户信息
        $customerRequest = $formatParam['customer'] ?? [];
        if (!$this->saveForm($customer['name'])) unset($customerRequest['customer_name']);
        if (!$this->saveForm($customer['category'])) unset($customerRequest['customer_category']);
        if (!$this->saveForm($customer['product'])) unset($customerRequest['customer_product']);
        if (!$this->saveForm($customer['type'])) unset($customerRequest['customer_area']);
        if (!$this->saveForm($customer['level'])) unset($customerRequest['customer_level']);

        //项目执行情况
        $processRequest = $formatParam['process'] ?? [];
        if (!$this->saveForm($process['state'])) unset($processRequest['process_state']);
        if (!$this->saveForm($process['end_date'])) unset($processRequest['process_end_date']);
        if (!$this->saveForm($process['external_link'])) unset($processRequest['process_external_link']);
        if (!$this->saveForm($process['memo'])) unset($processRequest['process_memo']);
        if (!$this->saveForm($process['spot'])) unset($processRequest['process_spot']);
        if (!$this->saveForm($process['problem'])) unset($processRequest['process_problem']);
        if (!$this->saveForm($process['solve'])) unset($processRequest['process_solve']);
        if (!$this->saveForm($process['advice'])) unset($processRequest['process_advice']);
        if (!$this->saveForm($process['consistent'])) unset($processRequest['process_consistent']);
        if (!$this->saveForm($process['consistent_memo'])) unset($processRequest['process_consistent_memo']);
        if (!$this->saveForm($process['different'])) unset($processRequest['process_different']);
        if (!$this->saveForm($process['different_memo'])) unset($processRequest['process_different_memo']);
        if (!$this->saveForm($process['feedback'])) unset($processRequest['process_feedback']);

        //项目成本
        $costsRequest = $formatParam['costs'] ?? [];
        if (!$this->saveForm($costs['estimate'])) unset($costsRequest['costs_estimate']);
        if (!$this->saveForm($costs['estimated_proportion'])) unset($costsRequest['costs_estimated_proportion']);
        if (!$this->saveForm($costs['real'])) unset($costsRequest['costs_real']);
        if (!$this->saveForm($costs['real_proportion'])) unset($costsRequest['costs_real_proportion']);
        if (!$this->saveForm($costs['external_link'])) unset($costsRequest['costs_external_link']);

        //合同信息
        $contractRequest = $formatParam['contract'] ?? [];
        if (!$this->saveForm($contract['create_time'])) unset($contractRequest['contract_create_time']);
        if (!$this->saveForm($contract['archive_time'])) unset($contractRequest['contract_archive_time']);
        if (!$this->saveForm($contract['express_no'])) unset($contractRequest['contract_express_no']);
        if (!$this->saveForm($contract['external_link'])) unset($contractRequest['contract_external_link']);
        if (!$this->saveForm($contract['anticipated_initial'])) unset($projectRequest['project_anticipated_initial']);
        if (!$this->saveForm($contract['initial'])) unset($contractRequest['contract_initial']);
        if (!$this->saveForm($contract['anticipated_initial_time'])) unset($projectRequest['project_anticipated_initial_time']);
        if (!$this->saveForm($contract['initial_time'])) unset($contractRequest['contract_initial_time']);
        if (!$this->saveForm($contract['initial_bill_time'])) unset($contractRequest['contract_initial_bill_time']);
        if (!$this->saveForm($contract['initial_bill_amount'])) unset($contractRequest['contract_initial_bill_amount']);
        if (!$this->saveForm($contract['initial_title'])) unset($contractRequest['contract_initial_title']);
        if (!$this->saveForm($contract['initial_express_no'])) unset($contractRequest['contract_initial_express_no']);
        if (!$this->saveForm($contract['anticipated_middle'])) unset($projectRequest['project_anticipated_middle']);
        if (!$this->saveForm($contract['middle'])) unset($contractRequest['contract_middle']);
        if (!$this->saveForm($contract['anticipated_middle_time'])) unset($projectRequest['project_anticipated_middle_time']);
        if (!$this->saveForm($contract['middle_time'])) unset($contractRequest['contract_middle_time']);
        if (!$this->saveForm($contract['middle_bill_time'])) unset($contractRequest['contract_middle_bill_time']);
        if (!$this->saveForm($contract['middle_bill_amount'])) unset($contractRequest['contract_middle_bill_amount']);
        if (!$this->saveForm($contract['middle_title'])) unset($contractRequest['contract_middle_title']);
        if (!$this->saveForm($contract['middle_express_no'])) unset($contractRequest['contract_middle_express_no']);
        if (!$this->saveForm($contract['anticipated_tail'])) unset($projectRequest['project_anticipated_tail']);
        if (!$this->saveForm($contract['tail'])) unset($contractRequest['contract_tail']);
        if (!$this->saveForm($contract['anticipated_tail_time'])) unset($projectRequest['project_anticipated_tail_time']);
        if (!$this->saveForm($contract['tail_time'])) unset($contractRequest['contract_tail_time']);
        if (!$this->saveForm($contract['tail_bill_time'])) unset($contractRequest['contract_tail_bill_time']);
        if (!$this->saveForm($contract['tail_bill_amount'])) unset($contractRequest['contract_tail_bill_amount']);
        if (!$this->saveForm($contract['tail_title'])) unset($contractRequest['contract_tail_title']);
        if (!$this->saveForm($contract['tail_express_no'])) unset($contractRequest['contract_tail_express_no']);
        if (!$this->saveForm($contract['memo'])) unset($contractRequest['contract_memo']);
        if (!$this->saveForm($contract['state_memo'])) unset($contractRequest['contract_state_memo']);

        //项目信息
        if (!$this->saveForm($project['type'])) unset($projectRequest['project_type']);
        if (!$this->saveForm($project['img'])) unset($projectRequest['project_img']);
        if (!$this->saveForm($project['no'])) unset($projectRequest['project_no']);
        if (!$this->saveForm($project['subject'])) unset($projectRequest['project_subject']);
        if (!$this->saveForm($project['name'])) unset($projectRequest['project_name']);
        if (!$this->saveForm($project['money'])) unset($projectRequest['project_money']);
        if (!$this->saveForm($project['start_date'])) unset($projectRequest['project_start_date']);
        if (!$this->saveForm($project['start_date'])) unset($projectRequest['project_end_date']);
        if (!$this->saveForm($project['company_type'])) unset($projectRequest['project_company_type']);
        if (!$this->saveForm($project['company_name'])) unset($projectRequest['project_company_name']);
        if (!$this->saveForm($project['company_contact'])) unset($projectRequest['project_company_contact']);
        if (!$this->saveForm($project['rebate_rate'])) unset($projectRequest['project_rebate_rate']);
        if (!$this->saveForm($project['rebate'])) unset($projectRequest['project_rebate']);
        if (!$this->saveForm($project['external_link'])) unset($projectRequest['project_external_link']);
        if (!$this->saveForm($project['memo'])) unset($projectRequest['project_memo']);
        if (!$this->saveForm($project['contracts'])) unset($projectRequest['project_contract']);
        if (!$this->saveForm($project['mcn'])) unset($projectRequest['project_mcn_uid']);
        if (!$this->saveForm($mcn['mcn'])) {
            unset($projectRequest['project_mcn_source']);
            unset($projectRequest['project_mcn_form']);
            unset($projectRequest['project_mcn_out']);
            unset($projectRequest['project_mcn_out_text']);
            unset($projectRequest['project_mcn_product']);
            unset($projectRequest['project_mcn_memo']);
        }


        //返点信息
        $rebateRequest = $formatParam['project_rebates'] ?? [];
        if (!$this->saveForm($rebate['rebate'])) unset($rebateRequest['project_rebates']);

        if (!empty($responsibleRequest['pm_extra'])) $extend += ['pm_extra' => $responsibleRequest['pm_extra']];
        $extend += $customerRequest;
        $extend += $processRequest;
        $extend += $costsRequest;
        $extend += $contractRequest;
        $extend += $projectRequest;
        $extend += $rebateRequest;

        if (isset($extend['project_contract']) && !strlen($extend['project_contract'])) throw new Exception('合作内容为必填项');
        if (isset($extend['project_img']) && !strlen($extend['project_img'])) throw new Exception('客户明确合作意向沟通凭证为必填项');
        if ($id == 0 && empty($extend['project_no'])) $extend['project_no'] = self::generateProjectNo();

        $responsible = $responsibleRequest;
        $exists = BizProjectResponsibilityModel::existsList($id);
        $existsResponsibleMap = [];
        $hasMcn = ($extend['project_mcn_uid'] ?? 0) == 1;
        if ($exists) {
            foreach ($exists as $v) {
                if (BizProjectResponsibilityModel::isNormal($v['status'])) {
                    $existsResponsibleMap[BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_NAME_MAP[$v['type']]][$v['admin_id']] = $v['admin_id'];
//                    if ($v['type'] == BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_MCN) {
//                        $hasMcn = true;
//                    }
                }
            }
        }

        //mcn栏自动添加  项目责任方权限管理 中 MCN责任方 对应组长
        if ($hasMcn && ($responsible['responsible_mcn'] ?? '') == '') {
            $rs = BizProjectGroupModel::getResponsibleLeader([BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_MCN]);
            $responsible_mcn = $rs ? array_column($rs, 'admin_id') : [];
            $responsible['responsible_mcn'] = $responsible_mcn ? implode(',', $responsible_mcn) : '';
        }
        $info = BizProjectModel::dataSelectInfo(['id' => $id]);

        list($project_id, $notice, $mcnNotice, $responsibleMap) = BizProjectModel::action(function () use ($id, $extend, $responsible) {
            $condition = $id ? ['id' => $id] : [];
            $project_category = $extend['customer_category'] ?? null;
            unset($extend['customer_category']);
            //主表入库操作
            $rs = $extend ? BizProjectModel::addData($extend + $condition) : true;
            if (!$rs) throw new Exception('商业项目主表保存失败');
            $project_id = $id ?: BizProjectModel::id();
            if (empty($project_id)) throw new Exception('获取id失败');
            $exists = BizProjectResponsibilityModel::existsList($project_id);
            $existsMap = [];
            foreach ($exists as $v) {
                $existsMap[$v['type']][$v['admin_id']] = $v;
            }
            //合作品类存储
            if ($project_category) {
                BizProjectPRelationIdsModel::saveProjectRelationIds($project_id, $project_category);
            }
            if (empty($responsible)) return [$project_id, [], [], []];
            $rows = [];
            $map = [
                BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_OWNER => $this->adminId(),
                BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_FINANCE => $extend['project_subject'] == 0 ? 'verawang,luolina' : 'verawang,zhangxiaoyu', //'liuxinhua,wangjianwei' : 'liuxinhua,tangyiwan',
                BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_LEGAL => 'liao', //'dongxiaorong'
            ];
            if (isset($responsible['responsible_seller'])) $map[BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_SELLER] = $responsible['responsible_seller'];
            if (isset($responsible['responsible_mcn'])) $map[BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_MCN] = $responsible['responsible_mcn'];
            if (isset($responsible['responsible_planner'])) $map[BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_PLANNER] = $responsible['responsible_planner'];
            if (isset($responsible['responsible_medium'])) $map[BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_MEDIUM] = $responsible['responsible_medium'];
            if (isset($responsible['responsible_pm'])) $map[BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_PM] = $responsible['responsible_pm'];

            $create = [];
            $mcnNotice = [];
            $seller = [];
            $emailResponsible = [];

            foreach ($map as $key => $v) {
                $isCreate = !in_array($key, [BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_MCN, BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_PLANNER]);
                $isMcn = $key == BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_MCN;
                $find = $existsMap[$key] ?? [];
                if (empty($v)) {
                    $arr = [];
                } else {
                    $arr = is_string($v) ? explode(',', $v) : $v;
                }

                if ($key == BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_OWNER && $find) {
                    $arr = [key($find)];
                }
                foreach ($arr as $admin_id) {
//                    if ($key == BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_SELLER) $seller[$admin_id] = $admin_id;
                    if (isset($find[$admin_id])) {
                        $status = $find[$admin_id]['status'];
                        if (!BizProjectResponsibilityModel::isNormal($status)) {
                            //恢复记录状态
                            $rows[] = ['id' => $find[$admin_id]['id'], 'status' => BizProjectResponsibilityModel::normalStatus()];
                            if ($isMcn) $mcnNotice[$admin_id] = $admin_id;
                        } else {
                            $emailResponsible[BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_NAME_MAP[$key]][$admin_id] = $admin_id;
                        }
                        unset($find[$admin_id]);
                    } else {
                        //新增记录
                        $rows[] = ['project_id' => $project_id, 'type' => $key, 'admin_id' => $admin_id];
                        if ($isCreate) $create[$admin_id] = $admin_id;
                        if ($isMcn) $mcnNotice[$admin_id] = $admin_id;
                    }
                }
                //删除没有处理的
                foreach ($find as $item) {
                    $rows[] = ['id' => $item['id'], 'status' => BizProjectResponsibilityModel::delStatus()];
                    if (BizProjectResponsibilityModel::isNormal($item['status'])) {
                        $emailResponsible[BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_NAME_MAP[$key]][$item['admin_id']] = $item['admin_id'];
                    }
                }
            }

            foreach ($rows as $row) {
                BizProjectResponsibilityModel::addData($row);
            }
            if ($create) $create += $seller;
            return [$project_id, $create, $mcnNotice, $emailResponsible];
        });

        try {
            //项目创建成功发送邮件
            if ($id > 0) $this->makeEmailNotice($id, $info, $extend, $responsible, $project_id, $existsResponsibleMap);
            if ($this->send) $this->sendEmail($id, $extend, $responsible, $project_id, $notice, $mcnNotice);
        } catch (\Exception $e) {
            throw new \Exception('项目创建成功,发送邮件失败:' . $e->getMessage() . " line:". $e->getLine() . " file:" . $e->getFile());
        }
    }

    public static function responsibleToArray($admin): array
    {
        if (is_array($admin)) return $admin;
        return $admin ? explode(',', $admin) : [];
    }
    /**
     * @throws Exception
     */
    private function sendEmail($id, $extend, $responsible, $project_id, $notice, $mcnNotice)
    {
        Log::info("商业记录邮件日志", [$id, $extend, $responsible, $project_id, $notice, $mcnNotice]);
        $groupInfo = BizProjectGroupModel::getGroupInfoByAdminId($this->adminId());
        $groupInfo = current($groupInfo);
        if (empty($groupInfo)) throw new \Exception('不属于任何组,无法发送邮件');
        $customerMap = BizProjectCustomerModel::adminNameOptions();
        $customerName = $customerMap[$extend['customer_name'] ?? ''];
        $createTime = date("Y-m-d H:i:s");
        $projectName = $extend['project_name'] ?? '';
        $projectType = self::PROJECT_TYPE_MAP[$extend['project_type']] ?? '';
        $projectStartDate = $extend['project_start_date'] ?? '';
        $projectEndDate = $extend['project_end_date'] ?? '';
        $projectNo = $extend['project_no'] ?? '';
        $projectMoney = $extend['project_money'] ?? '';
        $projectMemo = $extend['project_memo'] ?? '';
        $processMemo = $extend['process_memo'] ?? '';

        if (empty($projectName) || empty($projectType || empty($projectStartDate) || empty($projectEndDate) || empty($projectNo))) {
            if (!empty($id)) {
                $bizPro = BizProjectModel::dataSelectInfo(['id' => $id]);
                $projectName = $projectName ?: $bizPro['project_name'];
                $projectType = $projectType ?: self::PROJECT_TYPE_MAP[$bizPro['project_type']];
                $projectStartDate = $projectStartDate ?: $bizPro['project_start_date'];
                $projectEndDate = $projectEndDate ?: $bizPro['project_end_date'];
                $projectNo = $projectNo ?: $bizPro['project_no'];
                $projectMoney = $projectMoney ?: $bizPro['project_money'];
                $projectMemo = $projectMemo ?: $bizPro['project_memo'];
            }
        }

        $seller = self::responsibleToArray($responsible['responsible_seller']);
        $emailSeller = $seller;
        $mcn = self::responsibleToArray($responsible['responsible_mcn']);
        $planner = self::responsibleToArray($responsible['responsible_planner']);
        $medium = self::responsibleToArray($responsible['responsible_medium']);
        $pm = self::responsibleToArray($responsible['responsible_pm']);
        $cc = $this->getLeaderEmailByUser($seller);
//        $email = BizProjectGroupModel::getLeaderIdByAdminId(array_merge($pm, $medium));
        $email = $this->getLeaderEmail([BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_PM,BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_MEDIUM,BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_PLANNER], false);
        BeerUsUser::searchId($this->adminId());
        BeerUsUser::searchId($seller);
        BeerUsUser::searchId($mcn);
        BeerUsUser::searchId($planner);
        BeerUsUser::searchId($medium);
        BeerUsUser::searchId($pm);
        $admin = BeerUsUser::afterGetRowsMap($this->adminId());
        $seller = implode(',', BeerUsUser::afterGetRowsMap($seller));
        $mcn = implode(',', BeerUsUser::afterGetRowsMap( $mcn));
        $planner = implode(',', BeerUsUser::afterGetRowsMap($planner));
        $medium = implode(',', BeerUsUser::afterGetRowsMap($medium));
        $pm = implode(',', BeerUsUser::afterGetRowsMap($pm));
        $link = admin_url(BizProjectProject::getRoute()->getEditRoute($project_id));
        $header = <<<EMAIL
<br/>{$groupInfo['name']} {$admin} 于 {$createTime} ， 新建了项目工单，请安排后续工作。
EMAIL;
        $body = <<<BODY
<br/>
<br/>项目编号：{$projectNo}
<br/>合作品牌：{$customerName}
<br/>项目名称：$projectName
<br/>项目金额：{$projectMoney}
<br/>项目周期：{$projectStartDate} - {$projectEndDate}
<br/>项目信息备注说明：{$projectMemo}
<br/>项目执行备注说明：{$processMemo}
<br/>
<br/>当前项目责任方：
<br/>销售：$seller
<br/>MCN：$mcn
<br/>策划：$planner
<br/>媒介：$medium
<br/>PM：$pm
<br/>
<br/>项目链接：$link
BODY;
        $bodyNoMoney = <<<BODY
<br/>
<br/>项目编号：{$projectNo}
<br/>合作品牌：{$customerName}
<br/>项目名称：$projectName
<br/>项目周期：{$projectStartDate} - {$projectEndDate}
<br/>项目信息备注说明：{$projectMemo}
<br/>项目执行备注说明：{$processMemo}
<br/>
<br/>当前项目责任方：
<br/>销售：$seller
<br/>MCN：$mcn
<br/>策划：$planner
<br/>媒介：$medium
<br/>PM：$pm
<br/>
<br/>项目链接：$link
BODY;

        $tips = <<<EMAIL
<br/>您有一个新工单，请及时跟进。请项目所属销售注意项目执行备注以及项目责任方变动
EMAIL;

        $title = "【项目工单-{$projectType}】$projectName";
        if ($id == 0) {
            $this->sendMail($email, $title, $header . $body, null, '', $cc);
        }
        if ($emailSeller) {
            $this->sendMail($this->email($emailSeller), $title, $tips . $body);
        }
        if ($notice) {
            $this->sendMail($this->email($notice), $title, $tips . $body);
        }
        if ($mcnNotice) {
            $cc = $this->getLeaderEmail([BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_MCN]);
            $this->sendMail($this->email($mcnNotice), $title, $tips . $bodyNoMoney, null, '', $cc);
        }
    }

    /**
     * @param $id mixed 项目id
     * @param $info mixed 旧的记录
     * @param $extend mixed 表单提交的记录
     * @param $responsible mixed 表单提交的责任方记录
     * @param $project_id mixed 最终的项目id
     * @param $existsResponsibleMap  mixed 旧的责任方全部记录
     * @throws Exception
     */
    private function makeEmailNotice($id, $info, $extend, $responsible, $project_id, $existsResponsibleMap)
    {
        $groupInfo = BizProjectGroupModel::getGroupInfoByAdminId($this->adminId());
        $groupInfo = current($groupInfo);
        if (empty($groupInfo)) throw new \Exception('不属于任何组,无法发送邮件');
        $customerMap = BizProjectCustomerModel::adminNameOptions();
        $customerName = $customerMap[$extend['customer_name'] ?? ''];
        $createTime = date("Y-m-d H:i:s");

        $extend += $responsible;
        //如果存在旧的记录, 追加至提交的记录
        if ($info) {
            $info['project_start_date'] = date("Y-m-d", strtotime($info['project_start_date']));
            $info['project_end_date'] = date("Y-m-d", strtotime($info['project_end_date']));
            $info['responsible_mcn'] = implode(",", $existsResponsibleMap['mcn'] ?? []);
            $info['responsible_planner'] = implode(",", $existsResponsibleMap['planner'] ?? []);
            $info['responsible_medium'] = implode(",", $existsResponsibleMap['medium'] ?? []);
            $info['responsible_pm'] = implode(",", $existsResponsibleMap['pm'] ?? []);
            $extend += $info;
        }

        //查询最终的责任方数据
        $seller = $responsible['responsible_seller'] ?? implode(',', $existsResponsibleMap['seller'] ?? []);
        $mcn = $responsible['responsible_mcn'] ?? implode(',', $existsResponsibleMap['mcn'] ?? []);
        $planner = $responsible['responsible_planner'] ?? implode(',', $existsResponsibleMap['planner'] ?? []);
        $medium = $responsible['responsible_medium'] ?? implode(',', $existsResponsibleMap['medium'] ?? []);
        $pm = $responsible['responsible_pm'] ?? implode(',', $existsResponsibleMap['pm'] ?? []);

        BeerUsUser::searchId($this->adminId());
        BeerUsUser::searchId($seller);
        BeerUsUser::searchId($mcn);
        BeerUsUser::searchId($planner);
        BeerUsUser::searchId($medium);
        BeerUsUser::searchId($pm);
        $admin = BeerUsUser::afterGetRowsMap($this->adminId());

        $this->emailNotice['_admin'] = $admin;
        $this->emailNotice['_seller'] = explode(',', $seller);
        $this->emailNotice['_mcn'] = explode(',', $mcn);
        $this->emailNotice['_planner'] = explode(',', $planner);
        $this->emailNotice['_medium'] = explode(',', $medium);
        $this->emailNotice['_pm'] = explode(',', $pm);
        $this->emailNotice['_group_name'] = $groupInfo['name'];
        $this->emailNotice['_project_name'] = $extend['project_name'] ?? '';
        $this->emailNotice['_link'] = admin_url(BizProjectProject::getRoute()->getEditRoute($project_id));

        $seller = implode(',', BeerUsUser::afterGetRowsMap(explode(',', $seller)));
        $mcn = implode(',', BeerUsUser::afterGetRowsMap(explode(',', $mcn)));
        $planner = implode(',', BeerUsUser::afterGetRowsMap(explode(',', $planner)));
        $medium = implode(',', BeerUsUser::afterGetRowsMap(explode(',', $medium)));
        $pm = implode(',', BeerUsUser::afterGetRowsMap(explode(',', $pm)));

        //项目信息变更
        $extendProjectContract = json_decode($extend['project_contract'], true);
        $rows = [];
        if ($extendProjectContract) {
            foreach ($extendProjectContract as $v) {
                $rows[] = implode("; ", ['合作内容: ' . $v['content'], 'KPI: ' .  $v['kpi'], '上线时间: ' .  ($v['online_date_start'] . " ~ " . $v['online_date_end'])]);
            }
        }
        $projectMap = [
            ['project_no', '项目编号：' . $extend['project_no']],
            ['customer_name', '合作品牌：' . $customerName],
            ['project_type', '项目下单类型：'. self::PROJECT_TYPE_MAP[$extend['project_type']] ?? ''],
            ['project_subject', '项目主体：'. self::PROJECT_SUBJECT_MAP[$extend['project_subject']] ?? ''],
            ['project_name', '项目名称：'. $extend['project_name']],
            ['project_money', '项目金额：'. $extend['project_money']],
            [['project_start_date', 'project_end_date'], '项目周期：'. ($extend['project_start_date'] . "-" . $extend['project_end_date']), 'project_date_range'],
            ['project_company_type', '签约公司类型：'. self::COMPANY_TYPE_MAP[$extend['project_company_type'] ?? '']],
            ['project_company_name', '签约公司名称：'. $extend['project_company_name']],
            ['project_company_contact', '签约公司对接方式：'. $extend['project_company_contact']],
            ['project_external_link', '项目资料云盘链接：'. $extend['project_external_link']],
            ['project_contract', '合作内容：<br/>'. implode("<br/>", $rows)],
            ['project_memo', '项目信息备注说明：'. $extend['project_memo']],
            ['process_memo', '项目执行备注说明：'. $extend['process_memo']],
            ['project_rebate_rate', '返点比例：'. $extend['project_rebate_rate']],
            ['project_rebate', '返点金额：'. $extend['project_rebate']],
        ];

        //项目执行情况变更
        $processMap = [
            ['process_state', '项目状态：' . BizProjectProject::PROCESS_STATE_MAP[$extend['process_state']]],
            ['process_end_date', '项目结案时间：' . $extend['process_end_date']],
            ['process_external_link', '项目结案云盘链接：' . $extend['process_external_link']],
            ['process_memo', '项目执行备注：' . $extend['process_memo']],
            ['process_spot', '项目亮点：' . $extend['process_spot']],
            ['process_problem', '项目问题：' . $extend['process_problem']],
            ['process_solve', '项目问题解决方案：' . $extend['process_solve']],
            ['process_advice', '后续建议：' . $extend['process_advice']],
            ['process_consistent_memo', '客户需求与交付差异点：' . $extend['process_consistent_memo']],
            ['process_different_memo', '策划方案到执行落地交付差异点：' . $extend['process_different_memo']],
            ['process_feedback', '项目满意度：' . $extend['process_feedback']],
        ];

        //合同信息变更
        $contract_info_fields = [
            'contract_initial','contract_initial_time','contract_initial_title','contract_initial_express_no',
            'contract_middle','contract_middle_time','contract_middle_title','contract_middle_express_no',
            'contract_tail','contract_tail_time','contract_tail_title','contract_tail_express_no','contract_memo','contract_state_memo',
            'contract_initial_bill_time','contract_initial_bill_amount','contract_middle_bill_time','contract_middle_bill_amount',
            'contract_tail_bill_time','contract_tail_bill_amount',
            'project_anticipated_initial','project_anticipated_initial_time','project_anticipated_middle',
            'project_anticipated_middle_time','project_anticipated_tail','project_anticipated_tail_time'
        ];
        $contractMap = [
            ['contract_create_time', '合同订立时间：' . $extend['contract_create_time']],
            ['contract_archive_time', '合同归档时间：' . $extend['contract_archive_time']],
            ['contract_express_no', '合同邮寄快递单号：' . $extend['contract_express_no']],
            ['contract_external_link', '合同链接：' . $extend['contract_external_link']],
            [$contract_info_fields, '合同收款信息：' . '请在项目中查看', 'contract_info'],

        ];
        //项目成本变更
        $costsMap = [
            ['costs_estimate', '成本预估金额：' . $extend['costs_estimate']],
            ['costs_estimated_proportion', '成本预估占比（%）：' . $extend['costs_estimated_proportion']],
            ['costs_real', '实际成本金额：' . $extend['costs_real']],
            ['costs_real_proportion', '实际成本占比（%）：' . $extend['costs_real_proportion']],
            ['costs_external_link', '项目成本云盘链接：' . $extend['costs_external_link']],

        ];
        //项目责任方变更
        $responsibleMap = [
            ['responsible_mcn', 'MCN：' . $mcn],
            ['responsible_planner', '策划：' . $planner],
            ['responsible_medium', '媒介：' . $medium],
            ['responsible_pm', 'pm：' . $pm],
        ];

        if ($this->changeCheck($projectMap, $extend, $info)) $this->sendProjectChangeMail();
        if ($this->changeCheck($processMap, $extend, $info)) $this->sendProcessChangeMail();
        if ($this->changeCheck($contractMap, $extend, $info)) $this->sendContractChangeMail();
        if ($this->changeCheck($costsMap, $extend, $info)) $this->sendCostsChangeMail();
        if ($this->changeCheck($responsibleMap, $extend, $info)) $this->sendResponsibleChangeMail();
    }

    private function sendProjectChangeMail()
    {
        $title = "【项目信息变更】{$this->emailNotice['_project_name']}";
        $header = <<<EMAIL
<br/>{$this->emailNotice['_admin']} 变更了项目工单，标红字体为变更项，请查看变更内容，若邮件中没有字段标红，请点击项目链接查看返点比例或返点金额的变更。
EMAIL;
        $body = <<<BODY
<br/>
<br/>{$this->emailNotice['project_no']}
<br/>{$this->emailNotice['customer_name']}
<br/>{$this->emailNotice['project_type']}
<br/>{$this->emailNotice['project_subject']}
<br/>{$this->emailNotice['project_name']}
<br/>{$this->emailNotice['project_money']}
<br/>{$this->emailNotice['project_date_range']}
<br/>{$this->emailNotice['project_company_type']}
<br/>{$this->emailNotice['project_company_name']}
<br/>{$this->emailNotice['project_company_contact']}
<br/>{$this->emailNotice['project_external_link']}
<br/>{$this->emailNotice['project_contract']}
<br/>{$this->emailNotice['project_memo']}
<br/>{$this->emailNotice['process_memo']}
<br/>
<br/>项目链接：<a target="_blank" href="{$this->emailNotice['_link']}">编辑项目链接</a>
BODY;

        $sellerLeader = $this->getLeaderEmailByUser($this->emailNotice['_seller'], false);
        /**
         * 项目所属策划
         * 项目所属媒介
         * 项目所属pm
         * 抄送：销售组leader
         * yanmuxi@haohaozhu.com
        */
        $email = array_merge($this->emailNotice['_planner'], $this->emailNotice['_medium'], $this->emailNotice['_pm']);
        $leaders = $this->getLeaderEmail([BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_PM,BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_MEDIUM], false);
        $emails = $this->email($email);
        $emails = array_merge($emails, $leaders, $sellerLeader);
        $this->sendMail($emails, $title, $header . $body);

    }

    private function sendProcessChangeMail()
    {
        $title = "【项目执行情况变更】{$this->emailNotice['_project_name']}";
        $header = <<<EMAIL
<br/>{$this->emailNotice['_admin']} 变更了项目执行情况，请查看变更内容。
EMAIL;
        $body = <<<BODY
<br/>
<br/>{$this->emailNotice['project_no']}
<br/>{$this->emailNotice['project_name']}
<br/>{$this->emailNotice['process_state']}
<br/>{$this->emailNotice['process_memo']}
<br/>{$this->emailNotice['process_spot']}
<br/>{$this->emailNotice['process_problem']}
<br/>{$this->emailNotice['process_solve']}
<br/>{$this->emailNotice['process_advice']}
<br/>{$this->emailNotice['process_consistent_memo']}
<br/>{$this->emailNotice['process_different_memo']}
<br/>{$this->emailNotice['process_feedback']}
<br/>
<br/>项目链接：<a target="_blank" href="{$this->emailNotice['_link']}">编辑项目链接</a>
BODY;
        /**
         * liuyang@haohaozhu.com、
         * 项目所属销售
         * 项目所属媒介
        */
        $email = array_merge($this->emailNotice['_seller'], $this->emailNotice['_medium']);
        $emails = array_merge($this->email($email), ['liuyang@haohaozhu.com']);
        $this->sendMail($emails, $title, $header . $body);

    }

    private function sendContractChangeMail()
    {
        $title = "【合同签约收款信息变更】{$this->emailNotice['_project_name']}";
        $header = <<<EMAIL
<br/>{$this->emailNotice['_admin']} 变更了合同签约、合同收款信息，请查看变更内容。
EMAIL;
        $body = <<<BODY
<br/>
<br/>{$this->emailNotice['project_no']}
<br/>{$this->emailNotice['project_name']}
<br/>{$this->emailNotice['contract_create_time']}
<br/>{$this->emailNotice['contract_archive_time']}
<br/>{$this->emailNotice['contract_express_no']}
<br/>{$this->emailNotice['contract_external_link']}
<br/>{$this->emailNotice['contract_info']}
<br/>
<br/>项目链接：<a target="_blank" href="{$this->emailNotice['_link']}">编辑项目链接</a>
BODY;
        /**
         * 项目所属销售
         */
        $email = array_merge($this->emailNotice['_seller']);
        $this->sendMail($this->email($email), $title, $header . $body);
    }

    private function sendCostsChangeMail()
    {
        $title = "【项目成本变更】{$this->emailNotice['_project_name']}";
        $header = <<<EMAIL
<br/>{$this->emailNotice['_admin']} 变更了项目成本，请查看变更内容。
EMAIL;
        $body = <<<BODY
<br/>
<br/>{$this->emailNotice['project_no']}
<br/>{$this->emailNotice['project_name']}
<br/>{$this->emailNotice['costs_estimate']}
<br/>{$this->emailNotice['costs_estimated_proportion']}
<br/>{$this->emailNotice['costs_real']}
<br/>{$this->emailNotice['costs_real_proportion']}
<br/>{$this->emailNotice['costs_external_link']}
<br/>
<br/>项目链接：<a target="_blank" href="{$this->emailNotice['_link']}">编辑项目链接</a>
BODY;
        /**
         * 项目所属销售
         * 项目所属pm
         */
        $email = array_merge($this->emailNotice['_seller'], $this->emailNotice['_pm']);
        $this->sendMail($this->email($email), $title, $header . $body);
    }

    private function sendResponsibleChangeMail()
    {
        $title = "【项目责任方变更】{$this->emailNotice['_project_name']}";
        $header = <<<EMAIL
<br/>{$this->emailNotice['_admin']} 变更了项目责任方，请查看变更内容。
EMAIL;
        $body = <<<BODY
<br/>
<br/>{$this->emailNotice['project_no']}
<br/>{$this->emailNotice['project_name']}
<br/>{$this->emailNotice['responsible_mcn']}
<br/>{$this->emailNotice['responsible_planner']}
<br/>{$this->emailNotice['responsible_medium']}
<br/>{$this->emailNotice['responsible_pm']}
<br/>
<br/>项目链接：<a target="_blank" href="{$this->emailNotice['_link']}">编辑项目链接</a>
BODY;
        $email = array_merge($this->emailNotice['_seller']);
        $leaders = $this->getLeaderEmail([BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_MEDIUM], false);
        $emails = $this->email($email);
        $emails = array_merge($emails, $leaders);
        $this->sendMail($emails, $title, $header . $body);
    }

    /**
     * @throws Exception
     */
    public function delete($id)
    {
        $fieldAuth = BizProjectGroup::fieldAuth($this->adminId(), 'admin');
        if (!$this->exportField($fieldAuth['project_delete'])) throw new Exception("权限不足");
        return BizProjectModel::statusDelete($id);
    }

    public function getTotal(): int
    {
        return $this->total ?? BizProjectModel::statusTotal($this->getRequestCondition());
    }
}